// userSelector

(function ($, undefined) {

    // define the name of the UI component
    var ui_name = "userSelector"

    // initialize object
    var userSelector = $.userSelector = {

        // default values
        defaults: {
            displayChoosePanel: true,
            arrowPosition: 'after',
            isAutoComplete: true,
            canChooseEveryone: true,
            offsetY: 5,
            offsetX: 5,
            canMutipleSelect: true
        },

        setDefaults: function (defaultOptions) {
            this.defaults = $.extend({}, this.defaults, defaultOptions);
        }
    };

    $.fn.userSelector = function (options) {

        // method calling
        if (typeof options == 'string') {
            var args = Array.prototype.slice.call(arguments, 1),
			res;
            this.each(function () {
                var data = $.data(this, ui_name);
                if (data) {
                    var meth = data[options];
                    if (meth) {
                        var r = meth.apply(this, args);
                        if (res === undefined) {
                            res = r;
                        }
                    }
                }
            });
            if (res !== undefined) {
                return res;
            }
            return this;
        }

        // initialize options
        options = $.extend({}, userSelector.defaults, options);

        /* globle vars 
        -----------------------------------------------------------------------------*/
        var globle = {

            isUserSelectPanelDisplayed: false,
            isUserInfoLoaded: false,
            isChangingDept: false,

            allUserInfo: [],
            _allUserInfo: [],
            bindUserInfo: [],
            selectedUserInfo: [],
            disabledUserInfo: [],
            allDeptInfo: [],

            selectorPanel: null,
            userListPanel: null,
            btnShowPanelDom: null
        };

        this.each(function () {
            var _self = $(this);

            if (_self) {

                // 避免重复初始化
                if (_self.data('__initialized') == null) {
                    _self.data('__initialized', true)
                } else {
                    // 检测到已经初始化过，直接退出
                    return;
                }

                // 初始化 数据
                initailizeUserInfo();

                // 初始化 DOM 树
                initializeDom();
            }


            // initialize callback
            for (var key in options) {
                var value = options[key];
                if (typeof value == 'function') {
                    // bind callbacks
                    $(_self).bind(key, value);
                }
            }


            /* Private Methods
            -----------------------------------------------------------------------------*/

            function removeUserFromList(userId, userInfoList) {
                $(userInfoList).each(function (index, item) {
                    if (item.Id == userId) {
                        delete item;
                        userInfoList.splice(index, 1);
                    }
                });
            }

            function refreshSelectAllCheckbox() {
                // 所有选中的个数
                var selectedCountInCurrentPanel = $('label input:checkbox:checked', globle.userListPanel).length;
                // 算出所有没选中但是disable的个数
                var disabledLabels = $('label input:checkbox:disabled', globle.userListPanel);
                var disabledLabelsCount = disabledLabels.length;
                $(disabledLabels).each(function (index, item) {
                    // 把Disableed又选中的给去掉
                    if ($(item).attr('checked')) disabledLabelsCount--;
                });

                var isSelectAll = globle.bindUserInfo.length == selectedCountInCurrentPanel + disabledLabelsCount;
                $('.chk-select-all', globle.selectorPanel).attr('checked', isSelectAll);
            }

            function setUserToList(userList, userInfo, isSelected) {
                // 处理当前选中列表
                var isSelectedInList = false;
                $(userList).each(function (index, item) {
                    if (item.Id == userInfo.Id) {
                        // 在已经选中的列表里面，找到了
                        isSelectedInList = true;
                        if (!isSelected) {
                            // 如果找到了，并且没有选择，则从列表里去掉这厮
                            delete item;
                            userList.splice(index, 1);
                        }
                        return;
                    }
                });
                if (!isSelectedInList && isSelected) {
                    // 如果没找到，而且选择了，就把这厮加到列表去
                    userList.push(userInfo);
                }
            }


            function setUserIsSelected(userInfo, isSelected) {

                if (!options.canMutipleSelect) {
                    // 如果要选择新的，因为 不允许选择多个, 所以把当前选择的人全部给清空
                    if (isSelected) {
                        $(globle.selectedUserInfo).each(function (index, item) {
                            setUserIsSelected(item, false);
                        });
                    }
                }

                // 处理UI上的事情，高亮显示已经选中的用户
                var theLabel = $('.lbl-' + userInfo.Id, globle.userListPanel);
                if (theLabel.length > 0) {
                    $('input:checkbox', theLabel).attr('checked', isSelected)
                    if (isSelected) {
                        $(theLabel).addClass('selected');
                    } else {
                        $(theLabel).removeClass('selected');
                    }
                }
                refreshSelectAllCheckbox();

                setUserToList(globle.selectedUserInfo, userInfo, isSelected);

                if (!options.canMutipleSelect && isSelected && !globle.isChangingDept) {
                    // 选中单个人 那么直接关闭
                    globle.selectorPanel.contextPanel('close');
                }
            }

            function setUserIsDisabled(userInfo, isDisabled) {

                var theLabel = $('.lbl-' + userInfo.Id, globle.userListPanel);
                if (theLabel.length > 0) {
                    $('input:checkbox', theLabel).attr('disabled', isDisabled)
                    if (isDisabled) {
                        $(theLabel).removeClass('normal').addClass('disabled').data('isDisabled', true);
                    } else {
                        $(theLabel).removeClass('normal').addClass('disabled').data('isDisabled', false);
                    }
                }

                refreshSelectAllCheckbox();

                setUserToList(globle.disabledUserInfo, userInfo, isDisabled);
            }


            // 更新当前状态下的员工选择列表
            // 第一个参数为 everyone 或者 空 直接绑定所有人
            function refreshUserList(deptId) {
                if (deptId && deptId != "everyone") {
                    globle.bindUserInfo = [];
                    // 按照部门过滤
                    $(globle._allUserInfo).each(function (index, item) {
                        if (item.Dept.Id == deptId) {
                            globle.bindUserInfo.push(item);
                        }
                    });
                } else {
                    // 直接取出所有用户
                    globle.bindUserInfo = globle.allUserInfo;
                }

                // UI操作，把用户绑上去。。

                if (!globle.userListPanel) {
                    globle.userListPanel = $('<ul/>');
                    globle.userListPanel.appendTo(globle.selectorPanel);
                } else {
                    globle.userListPanel.empty();
                }

                var currentLi = null;
                var lineCount = 0;

                // 把所有人全部画到弹出框上面去
                $(globle.bindUserInfo).each(function (index, item) {
                    if (lineCount++ % 5 == 0) {
                        currentLi = $('<li/>').appendTo(globle.userListPanel);
                    }

                    var labelDom = $('<label/>')
                        .addClass('lbl-' + item.Id)
                        .addClass('normal')
                        .qtip({
                            content: item.Position.Description + '<br/>(' + item.Dept.DeptName + ')',
                            position: {
                                my: 'left bottom',
                                at: 'top middle'
                            }
                        })
                        .append(
                            $('<input/>')
                              .attr('type', 'checkbox')
                              .data('userInfo', item)
                              .change(function () {
                                  var userId = $(this).data('userInfo');
                                  var isChecked = $(this).attr('checked');
                                  setUserIsSelected(userId, isChecked);
                              })
                         )
                        .append(item.Name)
                        .appendTo(currentLi);
                });

                // 把所有已经选中的用户高亮显示并选中
                $(globle.selectedUserInfo).each(function (index, item) {
                    setUserIsSelected(item, true);
                });
                // 把所有已经禁用的用户加上属性并禁用
                $(globle.disabledUserInfo).each(function (index, item) {
                    setUserIsDisabled(item, true);
                });

                refreshSelectAllCheckbox();
            }

            function clearDom() {
                $(globle.btnShowPanelDom).remove();
                $(globle.selectorPanel).remove();
                $(globle.userListPanel).remove();

                globle.btnShowPanelDom = null;
                globle.selectorPanel = null;
                globle.userListPanel = null;

                globle.bindUserInfo = [];
                globle.selectedUserInfo = [];
                globle.disabledUserInfo = [];

                globle.isUserInfoLoaded = false;
            }

            function initializeDept() {
                globle.allDeptInfo = [];

                // 获得所有部门信息
                $(globle.allUserInfo).each(function (index, userInfo) {
                    var isAddToDeptList = false;
                    // 寻找是否已经加入了
                    $(globle.allDeptInfo).each(function (index, item) {
                        if (item.Id == userInfo.Dept.Id) {
                            isAddToDeptList = true;
                            return;
                        }
                    });
                    // 如果没找到，就加入到部门列表
                    if (!isAddToDeptList) {
                        globle.allDeptInfo.push(userInfo.Dept);
                    }
                });
            }

            function initailizeUserInfo() {
                if (!globle.isUserInfoLoaded) {
                    if (globle._allUserInfo.length == 0) {
                        var userInfos = EzDesk.Service.GetAllUserInfo_CacheSync();
                        $.extend(true, globle._allUserInfo, userInfos);
                        $.extend(true, globle.allUserInfo, userInfos);

                    }
                    else {
                        $.extend(true, globle.allUserInfo, globle._allUserInfo);
                    };

                    globle.isUserInfoLoaded = true;
                }

                initializeDept();
            }

            function initializeDom() {
                // 如果需要显示选择面板，那么加上箭头
                if (userSelector.defaults.displayChoosePanel) {
                    globle.btnShowPanelDom =
                        $('<span style="width:18px;height:18px;vertical-align:middle;margin-left:2px;"><span/>')
                        .button({
                            icons: {
                                primary: "ui-icon-search"
                            },
                            text: false
                        })
                        .click(function (event) {
                            innerToggle();
                            event.stopPropagation();
                        });
                    if (options.arrowPosition == "after") {
                        globle.btnShowPanelDom.insertAfter(_self);
                    } else if (options.arrowPosition == "before") {
                        globle.btnShowPanelDom.insertBefore(_self);
                    };
                }


                // 初始化用来选人的 panel
                globle.selectorPanel = $('<div class="userselector-selector-panel" style="display:none;"/>')
                    .appendTo('body');


                //************** 画个请选择提示上期
                var selectTipsDom = $('<h1/>').html("请选择员工:");

                var rightFuncPanelDom = $('<span style="float:right" />').appendTo(selectTipsDom);

                if (options.canMutipleSelect) {
                    var checkSelectAll = $('<input class="chk-select-all" type="checkbox"/>')
                        .click(function () {
                            var isTryToSelectAll = $(this).attr('checked');
                            // 点击全选时候，把当前panel里的人全部选中
                            $('label', globle.userListPanel).each(function (index, item) {
                                if (!$(item).data('isDisabled')) {
                                    setUserIsSelected($('input:checkbox', item).data('userInfo'), isTryToSelectAll);
                                }
                            });
                        });
                    var selectAllDom = $('<label/>')
                        .append(checkSelectAll)
                        .append('<span>全选</span>')
                        .appendTo(rightFuncPanelDom);
                }


                var selectDeptDom = $('<select style="margin: 0px 5px; padding: 0px;" class="select-dept"/>')

                // 绑定部门列表
                    .comboxBindingWithEmptyDefault(globle.allDeptInfo, 'DeptName', 'Id', '所有部门', 'everyone')
                    .change(function (e) {
                        globle.isChangingDept = true;
                        refreshUserList(e.target.value);
                        globle.isChangingDept = false;
                    })
                    .appendTo(rightFuncPanelDom);

                selectTipsDom.appendTo(globle.selectorPanel);

                //************** 画人的名单到界面上去
                refreshUserList("everyone");

                var selectFuncDom = $('<p style="float:right; margin-right: 30px"><input type="button" class="userselector-selector-btn-close" value="完成"/></p>')
                    .appendTo(globle.selectorPanel);
                $('.userselector-selector-btn-close', selectFuncDom).click(function () {
                    globle.selectorPanel.contextPanel('close');
                });
            }



            function innerToggle(parent) {
                globle.isUserSelectPanelDisplayed ? innerHidePanel() : innerShowPanel(parent);
            }

            function innerShowPanel(parent) {
                onPreOpenSelectPanel();

                globle.selectorPanel.contextPanel({
                    parent: parent ? parent : globle.btnShowPanelDom,
                    offsetY: options.offsetY,
                    offsetX: options.offsetX,
                    contextPanelClose: innerHidePanel
                });
                globle.isUserSelectPanelDisplayed = true;
            }

            function innerHidePanel() {
                onSelectorPanelClosed();
                globle.isUserSelectPanelDisplayed = false;
            }

            function findUser(userId) {
                var theUser = null;
                $(globle.allUserInfo).each(function (index, item) {
                    if (item.Id == userId) {
                        theUser = item;
                        return;
                    }
                });
                return theUser;
            }

            /* Callback Triggers
            -----------------------------------------------------------------------------*/

            function onSelectorPanelClosed() {
                var selectedGroups = null;
                if (globle.selectedUserInfo.length == globle.allUserInfo.length) {
                    // 全选了
                    selectedGroups = "everyone";
                }
                $(_self).trigger("selectorPanelClosed",
                    {
                        Users: globle.selectedUserInfo,
                        Groups: selectedGroups
                    });
            }

            function onPreOpenSelectPanel() {
                $(_self).trigger("preOpenSelectPanel");
            }




            function refreshDomAfterUserInfosChanged() {
                // 重新找出所有 部门
                initializeDept();

                // 重新绑定 部门
                var selectDept = $('.select-dept', globle.selectorPanel);
                var currentBindDeptValue = selectDept.val();
                selectDept.comboxBindingWithEmptyDefault(globle.allDeptInfo, 'DeptName', 'Id', '所有部门', 'everyone')

                selectDept.val(currentBindDeptValue);

                // 重新绑定当前页的 用户
                refreshUserList(selectDept.val());

            }

            /* Public Methods
            -----------------------------------------------------------------------------*/

            var publicMethods = {
                //                //set options
                //                option: function (name, value) {
                //                    if (value === undefined) {
                //                        return options[name];
                //                    }
                //                    options[name] = value;
                //                },
                toggle: innerToggle,

                getSelectMembers: function () {
                    return {
                        Users: globle.selectedUserInfo,
                        Groups: selectedGroups
                    };
                },

                setUserSelected: function (userId, isSelected) {
                    var theUser = findUser(userId);
                    if (theUser == null) return; // 如果这个用户不存在直接退出

                    setUserIsSelected(theUser, isSelected);
                },

                setUserDisabled: function (userId, isDisabled) {
                    // 1. 找到这个人
                    var theUser = findUser(userId);
                    if (theUser == null) return; // 如果这个用户不存在直接退出

                    // 2. 把这个人加入禁用列表
                    setUserIsDisabled(theUser, isDisabled);
                },

                reset: function () {
                    clearDom();
                    initailizeUserInfo();
                    //  回复初始状态
                    initializeDom();
                },

                removeUsers: function (userIds) {
                    // 批量处理用户删除
                    var userIdArray = userIds.split(',');
                    $(userIdArray).each(function (index, item) {
                        if (item) {
                            removeUserFromList(item, globle.allUserInfo);
                            removeUserFromList(item, globle.bindUserInfo);
                            removeUserFromList(item, globle.selectedUserInfo);
                            removeUserFromList(item, globle.disabledUserInfo);
                        }
                    });
                    refreshDomAfterUserInfosChanged();
                },

                initUsers: function (userIds) {
                    globle.allUserInfo = userIds;
                    globle._allUserInfo = userIds;

                    refreshDomAfterUserInfosChanged();
                }
            };

            $.data(this, ui_name, publicMethods);


        });

        return this;
    };



})(jQuery);
